package work.jame.blog.configuration.filter;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import work.jame.blog.configuration.security.LoginUser;
import work.jame.blog.framework.constant.HttpHeaderConstant;
import work.jame.blog.framework.exception.certificate.TokenException;
import work.jame.blog.framework.result.Result;
import work.jame.blog.framework.utils.http.WebUtils;
import work.jame.blog.framework.utils.redis.RedisService;
import work.jame.blog.framework.utils.redis.RedisUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * jwt认证过滤器
 * 目前没有啥需求能用到jwt,uuid也可以
 * 先保留着吧,留给以后扩展
 *
 * @author : Jame
 * @date : 2023-05-10 08:42
 **/
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {


    @Autowired
    private RedisService redisService;

    @Override
    protected void doFilterInternal(@NotNull HttpServletRequest request,
                                    @NotNull HttpServletResponse response,
                                    @NotNull FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(HttpHeaderConstant.TOKEN);
        if (!StringUtils.hasText(token)) {
            //websocket的情况
            token = request.getHeader(HttpHeaderConstant.SEC_WEBSOCKET_PROTOCOL);
            if(StringUtils.hasText(token)){
                response.setHeader(HttpHeaderConstant.SEC_WEBSOCKET_PROTOCOL,token);
            }
        }
        //放行不存在token的请求
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request, response);
            return;
        }
        JWT jwt;
        try {
            jwt = JWTUtil.parseToken(token);
        } catch (Exception e) {
            //忽略异常
            Result<?> result = Result.create(null, HttpStatus.UNAUTHORIZED.value(), "token错误,请重新登录");
            WebUtils.respondResult(WebUtils.getResponse(), result);
            return;
        }
        //jwt验证失败
        if (jwt.verify()) {
            filterChain.doFilter(request, response);
            return;
        }
        Object id = jwt.getPayload("id");
        //获取不到jwt中的信息
        if (Objects.isNull(id)) {
            filterChain.doFilter(request, response);
            return;
        }
        //不能直接强转long
        String loginKey = RedisUtils.getLoginKey(((Integer) id).longValue());
        LoginUser loginUser = redisService.getCacheObject(loginKey);
        //redis过期
        if (Objects.isNull(loginUser)) {
            Result<?> result = Result.create(null, HttpStatus.UNAUTHORIZED.value(), "凭证已过期,请重新登录");
            WebUtils.respondResult(WebUtils.getResponse(), result);
            return;
        }
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }

}
